package com.LeetCode.Hash;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * 字母异位分组
 */
public class SameOfBuildWords {
    //前26个素数
    int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
            31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
            73, 79, 83, 89, 97, 101};


    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<Integer, List<String>> map = new HashMap<>();

        for(String str : strs){
            int rootHash = 1;
            for(char c : str.toCharArray()){
                rootHash *= primes[c - 'a'] ;
            }

            if(map.containsKey(rootHash)){
                map.get(rootHash).add(str);
            }else{
                map.put(rootHash,new ArrayList<String>(){{
                    add(str);
                }});
            }
        }
        return new ArrayList<>(map.values());
    }

    @Test
    public void test(){
        String[] strs = {"eat","tea","tan","ate","nat","bat"};
        groupAnagrams(strs).forEach(System.out::println);
    }
}
